<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Providers\MyJwt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Redis;

class DefaultController extends Controller
{
    private $attribute;

    private $number;

    /**
     * Create a new controller instance.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        if (!$this->number) {
            $this->number = Redis::get(Cookie::get('PHPSESSID'));
        }
        if ($this->request->get('role') == 3) {
            session_start();
            \phpCAS::setDebug('./cas.log');
            \phpCAS::client(CAS_VERSION_2_0,'authserver.hznu.edu.cn',443,'/authserver',true);
            \phpCAS::setNoCasServerValidation();
            \phpCAS::handleLogoutRequests();
            \phpCAS::forceAuthentication();
            $this->attribute = \phpCAS::getAttributes();
        }
    }

    public function index()
    {
        if (!$this->number) {
            $this->number = $this->getNumber();
        }
        if ($this->number) {
            $ticket = $this->madeTicket();
            $user = User::where('is_del', 0)->where('number', $this->number)->first();
            if (!$user) {
                $user = new User();
                $user->number = $this->number;
                $user->realname = $this->getRealname();
                $user->birthday = date('Y-m-d H:i:s', time());
                $user->join_party_at = date('Y-m-d H:i:s', time());
                $user->role = 1;
                $user->summary = '';
                $user->created_at = date('Y-m-d H:i:s', time());
                $user->updated_at = date('Y-m-d H:i:s', time());
                $user->save();
                $this->registerCount();
            }

            $timeout = (int)((time()+7200)/3600)*3600;
            $jwt = new MyJwt();
            $jwt->payload['uid'] = $user->id;
            $jwt->payload['role'] = 3;
            $jwt->payload['timeout'] = $timeout;
            $jwt->payload['ticket'] = $ticket;
            $cacheKey = sprintf('pt:login:uid:%d', $user->id);
            Redis::setex($cacheKey, 7260, $timeout);
            $token = $jwt->encode($jwt->payload, MyJwt::ENCODE_KEY, $jwt->header['alg']);
            $this->loginCount();
            return redirect('/user/index.html?_token='.$token.'&role=3');
        }
        if ($this->request->get('_token')) {
            $token = $this->request->get('_token');
            $jwt = new MyJwt();
            $jwtCode = $jwt->decode($token, MyJwt::ENCODE_KEY);
            if ($jwtCode) {
                switch ($jwtCode['role']) {
                    case 1 : return redirect('/manager/user.html?_token='.$token.'&role='.$jwtCode['role']);
                    case 2 : return redirect('/department/index.html?_token='.$token.'&role='.$jwtCode['role']);
                    default: return $this->baseView('public.default.login', []);
                }
            }
        }
        return redirect('/login.html');
    }

    public function login()
    {
        return $this->baseView('public.default.login', []);
    }

    public function logout()
    {
        $token = $this->request->get('_token');
        if ($token) {
            $jwt = new MyJwt();
            $jwtCode = $jwt->decode($token, MyJwt::ENCODE_KEY);
            if ($jwtCode) {
                Redis::setex(sprintf('pt:login:uid:%d', $jwtCode['uid']), 1, null);
                if ($jwtCode['role'] == 3) {
                    if (!Redis::get(Cookie::get('PHPSESSID'))) {
                        \phpCAS::logout(['service' => 'https://authserver.hznu.edu.cn/authserver/logout?ticket='.$jwtCode['ticket'].'&service='.$this->domain]);
                        return redirect('https://authserver.hznu.edu.cn/authserver/logout?ticket='.$jwtCode['ticket'].'&service='.$this->domain);
                    } else {
                        Redis::setex(Cookie::get('PHPSESSID'), 1, null);
                        return redirect($this->domain);
                    }
                }
            }
        }

        return redirect($this->domain);
    }

    private function getNumber()
    {
        return $this->attribute['uid'];
    }

    private function getRealname()
    {
        return $this->attribute['userName'];
    }

    private function madeTicket()
    {
        return md5($this->number);
    }
}
